<template>
	<view class="app login" v-if="complete">
		<!-- 页面内容开始 -->
		<!-- 密码登录 和 验证码登录 -->
		<view class="content" v-if="['pwd', 'sms'].indexOf(loginWay) > -1">
			<!-- 头部logo -->
			<view class="header"><image class="logo" :src="logoImage"></image></view>
			<swiper duration="200" disable-touch style="height: 380rpx" :current="loginWay == 'pwd' ? 0 : 1">
				<swiper-item>
					<!-- 账号（手机号）+密码登录 -->
					<view class="form-view">
						<view class="form-item form-border">
							<input class="form-input" v-model="form1.username" type="text" :maxlength="50" placeholder="用户名/手机号" placeholder-style="'color':'#8e8e8e'" />
						</view>
						<view class="form-item form-border">
							<input class="form-input" v-model="form1.password" type="password" :maxlength="50" placeholder="密码" placeholder-style="'color':'#8e8e8e'" />
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<!-- 手机号+短信登录 -->
					<view class="form-view">
						<view class="form-item form-border">
							<input class="form-input" v-model="form1.mobile" type="text" :maxlength="50" placeholder="手机号" placeholder-style="'color':'#8e8e8e'" />
						</view>
						<view class="form-item form-border">
							<!-- 文本框 -->
							<input class="form-input" v-model="form1.code" type="number" :maxlength="6" placeholder="请输入短信验证码" placeholder-style="'color':'#8e8e8e'" />
							<!-- 验证码倒计时开始 -->
							<vk-data-verification-code
								:check-user-exist="true"
								seconds="60"
								:mobile="form1.mobile"
								type="login"
								custom-style="font-size: 28rpx;"
								@error="codeError"
							></vk-data-verification-code>
							<!-- 验证码倒计时结束 -->
						</view>
					</view>
				</swiper-item>
			</swiper>
			<!-- 密码和短信登录方式的切换 -->
			<view class="login-way-change">
				<label class="login-way-left" v-if="loginWay == 'pwd'" @click="savePwd = !savePwd">
					<checkbox class="checkbox" :checked="savePwd" active-color="#737373" shape="circle"></checkbox>
					<text>记住密码</text>
				</label>
				<view class="login-way-right">
					<text v-if="loginWay == 'pwd'" @click="loginWay = 'sms'">切换验证码登录</text>
					<text v-if="loginWay == 'sms'" @click="loginWay = 'pwd'">切换账号密码登录</text>
				</view>
			</view>

			<view class="submit-btn">
				<button class="btn success circle" hover-class="hover" @click="login" :plain="false" type="success" shape="circle" :hair-line="false" :disabled="loading">
					{{ agreement ? "登 录" : "请先同意用户协议" }}
				</button>
			</view>
			<!-- 其他登录 -->
			<view class="login-icon-title">
				<text v-if="(envH5 === 'h5-weixin' || ['mp-weixin', 'app-plus'].indexOf(platform) > -1) && loginMode && loginMode.length > 0">------------ 其他登录方式 ------------</text>
			</view>
			<view class="login-icon-view">
				<!-- #ifdef MP-WEIXIN -->
				<view class="login-icon-item" v-if="weixinLoginMode === 0">
					<u-icon name="weixin-fill" @click="loginWay = 'onekey'" size="80" color="#19be6b"></u-icon>
				</view>
				<view class="login-icon-item" v-else-if="loginMode.indexOf('weixin') > -1">
					<u-icon name="weixin-fill" @click="loginWeixin()" size="80" color="#19be6b"></u-icon>
				</view>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<view class="login-icon-item" v-if="loginMode.indexOf('onekey') > -1">
					<u-icon name="vk-icon-mobile" @click="loginByUniverify()" size="65" color="#3f3f3f"></u-icon>
				</view>
				<view class="login-icon-item" v-if="loginMode.indexOf('weixin') > -1">
					<u-icon name="weixin-fill" @click="loginWeixin()" size="80" color="#19be6b"></u-icon>
				</view>
				<!-- #endif -->
				<view class="login-icon-item" v-if="envH5 === 'h5-weixin' && loginMode.indexOf('weixin') > -1">
					<u-icon name="weixin-fill" @click="getH5WeixinCode" size="80" color="#19be6b"></u-icon>
				</view>
			</view>
			<!-- 底部信息 -->
			<view class="footer">
				<label @click="agreement = !agreement">
					<checkbox class="footer-checkbox" :checked="agreement" active-color="#737373" shape="circle"></checkbox>
					<text>同意</text>
				</label>
				<navigator url="./agreement" open-type="navigate" class="link">《用户协议》</navigator>
				<view class="vk-contents">
					<navigator url="./forget" open-type="navigate" style="margin-left: 20rpx">找回密码</navigator>
					<text class="center-line">|</text>
					<navigator url="./register" open-type="navigate">注册账号</navigator>
				</view>
			</view>
		</view>

		<!-- 一键登录 -->
		<view class="content" v-else-if="['onekey'].indexOf(loginWay) > -1">
			<!-- 头部logo -->
			<view class="header" style="margin-top: 200rpx"><image class="logo" :src="logoImage"></image></view>

			<view class="submit-btn">
				<!-- #ifdef MP-WEIXIN -->
				<template v-if="weixinLoginMode === 0">
					<button v-if="!agreement" class="btn success circle" hover-class="hover" :plain="false" type="success" shape="circle" :hair-line="false" @click="agreementLogin">
						请先同意用户协议
					</button>
					<button
						v-else
						class="btn success circle"
						hover-class="hover"
						open-type="getPhoneNumber"
						@getphonenumber="loginByWeixinPhoneNumber"
						:plain="false"
						type="success"
						shape="circle"
						:hair-line="false"
						:disabled="loading"
					>
						{{ showLogin ? "微信一键登录" : "加载中..." }}
					</button>
				</template>
				<template v-else>
					<button v-if="!agreement" class="btn success circle" hover-class="hover" :plain="false" type="success" shape="circle" :hair-line="false" @click="agreementLogin">
						请先同意用户协议
					</button>
					<button v-else class="btn success circle" hover-class="hover" @click="loginWeixin" :plain="false" type="success" shape="circle" :hair-line="false" :disabled="loading">
						{{ showLogin ? "微信登录" : "加载中..." }}
					</button>
				</template>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<button v-if="!agreement" class="btn success circle" hover-class="hover" :plain="false" type="success" shape="circle" :hair-line="false" @click="agreementLogin">
					请先同意用户协议
				</button>
				<button v-else class="btn success circle" hover-class="hover" @click="loginByUniverify" :plain="false" type="success" shape="circle" :hair-line="false" :disabled="loading">
					本机号码一键登录
				</button>
				<!-- #endif -->

				<!-- #ifdef H5 -->
				<template v-if="envH5 === 'h5-weixin'">
					<button v-if="!agreement" class="btn success circle" hover-class="hover" :plain="false" type="success" shape="circle" :hair-line="false" @click="agreementLogin">
						请先同意用户协议
					</button>
					<button
						v-else
						class="btn success circle"
						hover-class="hover"
						@click="getH5WeixinCode"
						:plain="false"
						type="success"
						shape="circle"
						:hair-line="false"
						:disabled="loading"
					>
						微信登录
					</button>
				</template>
				<!-- #endif -->
			</view>

			<!-- 密码和短信登录方式的切换 -->
			<view class="login-way-change" style="margin-top: 60rpx">
				<view class="login-way-right">
					<text @click="loginWay = 'pwd'">切换账号密码登录</text>
				</view>
			</view>

			<!-- 底部信息 -->
			<view class="footer" style="position: absolute; bottom: 100rpx; text-align: center; width: 100%">
				<label @click="agreement = !agreement">
					<checkbox class="footer-checkbox" :checked="agreement" active-color="#737373" shape="circle"></checkbox>
					<text>同意</text>
				</label>
				<navigator url="./agreement" open-type="navigate" class="link">《用户协议》</navigator>
				<!-- #ifdef MP-WEIXIN -->
				<text>和</text>
				<text class="link" @click="openPrivacyContract">《隐私协议》</text>
				<!-- #endif -->
			</view>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<!-- 微信小程序专用隐私授权弹窗组件 -->
		<vk-mall-privacy-popup position="bottom" @agree="userAgreement"></vk-mall-privacy-popup>
		<!-- #endif -->

		<!-- 登录成功后设置用户基础信息的弹窗 -->
		<set-user-base-info v-model="updateUserInfoPopup.show" :needInviteCode="updateUserInfoPopup.needInviteCode" @close="onUpdateUserInfo"></set-user-base-info>

		<!-- 页面内容结束 -->
	</view>
</template>

<script>
var vk = uni.vk; // vk依赖
import setUserBaseInfo from "./components/set-user-base-info";
export default {
	components: {
		setUserBaseInfo
	},
	data() {
		// 页面数据变量
		return {
			complete: false,
			// init请求返回的数据
			data: {},
			// 表单请求数据
			form1: {
				username: "", // 账号
				password: "", // 密码
				mobile: "", // 手机号
				code: "", // 短信验证码
				inviteCode: "" // 邀请码
			},
			logoImage: "/static/logo.png",
			loginWay: "pwd", // 登录方式 pwd：账号+密码登录 sms：手机+短信登录 onekey 一键登录
			agreement: false, // 是否同意用户协议，默认必须是未同意状态，否则可能会导致审核不通过（当同意过一次后，后面默认同意）
			savePwd: true, // 是否记住密码
			platform: "", // 平台信息
			envH5: "",
			h5WeixinAppId: "",
			loading: false,
			showLogin: false,
			// 其他登录方式 onekey 一键登录 weixin 微信登录
			loginMode: [],
			weixinLoginMode: 0,
			// 设置用户基础信息的弹窗数据
			updateUserInfoPopup: {
				show: false,
				data: {},
				needInviteCode: false
			}
		};
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options) {
		vk = uni.vk;
		this.init(options);
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() {},
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() {
		// #ifdef MP-WEIXIN
		uni.hideHomeButton();
		// #endif
	},
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() {},
	// 监听 - 点击右上角转发时
	onShareAppMessage(options) {},
	// 函数
	methods: {
		// 页面数据初始化函数
		init(options = {}) {
			let that = this;
			console.log("init: ", options);
			let agreement = vk.getStorageSync("vkmall-login.agreement");
			if (agreement) this.agreement = true;
			// #ifndef APP-PLUS || MP-WEIXIN
			that.complete = true;
			// #endif
			that.platform = vk.pubfn.getPlatform();

			// #ifndef APP-PLUS || H5 || MP-WEIXIN
			that.loginWay = "pwd";
			// #endif

			// #ifdef H5
			that.envH5 = vk.h5.getEnv();
			if (that.envH5 === "h5-weixin" && options.code) {
				that.loginWeixin(options);
			}
			if (that.envH5 === "h5-weixin") {
				that.complete = false;
				this.getMchInfo({
					success: data => {
						vk.setVuex("$user.mchInfo", data.mchInfo);
						let login_mode = vk.getVuex("$user.mchInfo.h5_weixin.login_mode") || 0;
						this.weixinLoginMode = login_mode;
						let loginModeArr = ["pwd", "onekey"];
						that.loginWay = loginModeArr[login_mode];
						if (that.getWeixinLoginType() !== "none") {
							that.loginMode.push("weixin");
						}
					},
					complete: () => {
						that.complete = true;
					}
				});
			}
			// #endif

			// #ifdef MP-WEIXIN
			that.loginWay = "onekey";
			// 需要先在onLoad内执行此函数
			vk.userCenter.code2SessionWeixin({
				loading: true,
				data: {
					needCache: true
				},
				success: data => {
					that.encryptedKey = data.encryptedKey;
					that.showLogin = true;
				}
			});
			this.getMchInfo({
				success: data => {
					vk.setVuex("$user.mchInfo", data.mchInfo);
					let login_mode = vk.getVuex("$user.mchInfo.mp_weixin.login_mode") || 0;
					this.weixinLoginMode = login_mode;
					let loginModeArr = ["onekey", "pwd", "onekey"];
					that.loginWay = loginModeArr[login_mode];
					if (that.getWeixinLoginType() !== "none") {
						that.loginMode.push("weixin");
					}
				},
				complete: () => {
					that.complete = true;
				}
			});
			// #endif
			// #ifdef APP-PLUS
			this.getMchInfo({
				success: data => {
					vk.setVuex("$user.mchInfo", data.mchInfo);
					if (that.getWeixinLoginType() !== "none") {
						that.loginMode.push("weixin");
					}
					uni.preLogin({
						provider: "univerify",
						success() {
							//预登录成功
							console.log("当前环境支持本机号码一键登录");
							if (vk.getVuex("$user.mchInfo.app.onekey_login")) {
								that.loginMode.push("onekey");
								that.loginWay = "onekey";
								that.loginByUniverify();
							}
						},
						fail(res) {
							// 预登录失败
							console.log("当前环境不支持本机号码一键登录", res);
						}
					});
				},
				complete: () => {
					that.complete = true;
				}
			});
			// #endif
			let logo = vk.getVuex("$user.mchInfo.logo");
			if (logo) that.logoImage = logo;

			that.form1.inviteCode = vk.getVuex("$user.inviteCode");
			if (that.form1.inviteCode) {
				// 检查下邀请码是否有效
				vk.callFunction({
					url: "client/salesman.pub_getInviteCodeInfo",
					loading: true,
					data: {
						invite_code: that.form1.inviteCode
					},
					success: data => {
						if (!data.status) {
							// 邀请码无效，弃之
							that.form1.inviteCode = "";
							vk.setVuex("$user.inviteCode", "");
						} else {
							// 邀请码有效
						}
					}
				});
			}
			let username = vk.getVuex("$user.login.username");
			let password = vk.getVuex("$user.login.password");
			let savePwd = vk.getVuex("$user.login.savePwd");
			let mobile = vk.getVuex("$user.login.mobile");
			if (username) that.form1.username = username;
			if (password) that.form1.password = password;
			if (mobile) that.form1.mobile = mobile;
			if (typeof savePwd === "boolean") that.savePwd = savePwd;
		},
		getMchInfo(obj={}){
			// 缓存模式（减少一次请求）
			let data = vk.getEventReadyData("getMchInfo");
			if (data) {
				data.mchInfo = vk.getVuex("$user.mchInfo"); // mchInfo可能会更新，因此再从vuex内重新读取下
				if (typeof obj.success === "function") obj.success(data);
				if (typeof obj.complete === "function") obj.complete(data);
			} else {
				// 实时模式（增加一次请求）
				vk.callFunction({
					url: "client/pub.getMchInfo",
					loading: true,
					...obj,
					success: (data) => {
						// 重新通知getMchInfo事件已准备就绪
						vk.notifyEventReady("getMchInfo", data);
						if (typeof obj.success === "function") obj.success(data);
					}
				});
			}
		},
		// 页面跳转
		pageTo(path) {
			vk.navigateTo(path);
		},
		// 账号密码登录
		login() {
			let that = this;
			let { loginWay, form1, agreement } = that;
			if (!agreement) {
				that.agreementLogin(that.login);
				return;
			}
			vk.pubfn.debounce(() => {
				if (loginWay === "pwd") {
					that.loginByPwd();
				} else if (loginWay === "sms") {
					that.loginBySms();
				}
			}, 500);
		},
		// 手机短信登录
		loginBySms() {
			let that = this;
			let { form1 } = that;
			let { mobile, code, inviteCode } = form1;
			if (!vk.pubfn.checkStr(mobile, "mobile")) {
				vk.toast("手机号格式错误");
				return;
			}
			if (!code) {
				vk.toast("请输入验证码");
				return;
			}
			vk.userCenter.loginBySms({
				data: {
					mobile,
					code,
					type: "login",
					inviteCode
				},
				success: data => {
					vk.setVuex("$user.login.mobile", mobile);
					that.loginSuccess(data);
				}
			});
		},
		// 账号密码登录
		loginByPwd() {
			let that = this;
			let { form1, savePwd } = that;
			let { username, password } = form1;
			if (username.length < 4) {
				vk.toast("账号至少4位数");
				return;
			}
			if (!vk.pubfn.checkStr(password, "pwd")) {
				vk.toast("密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
				return;
			}
			// 登录操作
			vk.userCenter.login({
				data: {
					username,
					password
				},
				success: data => {
					if (savePwd) {
						vk.setVuex("$user.login.username", username);
						vk.setVuex("$user.login.password", password);
					} else {
						vk.setVuex("$user.login.password", "");
					}
					vk.setVuex("$user.login.savePwd", savePwd);
					that.loginSuccess(data);
				}
			});
		},
		onUpdateUserInfo() {
			let that = this;
			if (vk.pubfn.isNotNull(that.updateUserInfoPopup.data)) {
				that.loginSuccess(that.updateUserInfoPopup.data, 1);
			}
		},
		// 微信一键手机号登录
		loginByWeixinPhoneNumber(e) {
			let that = this;
			let { form1, encryptedKey } = that;
			let { inviteCode } = form1;
			// 使用微信绑定的手机号登录/注册
			let { encryptedData, iv } = e.detail;
			if (!encryptedData || !iv) {
				return false;
			}
			vk.userCenter.loginByWeixinPhoneNumber({
				data: {
					encryptedData,
					iv,
					encryptedKey,
					inviteCode
				},
				success: data => {
					that.loginSuccess(data);
				}
			});
		},
		// 本机号码一键登录
		loginByUniverify() {
			let that = this;
			vk.userCenter.loginByUniverify({
				// 更多配置请查看 https://uniapp.dcloud.io/univerify
				univerifyStyle: {
					fullScreen: true, // 是否全屏显示(hbx3.1.5起支持全屏)，true表示全屏模式，false表示非全屏模式，默认值为false。
					backgroundColor: "#f5f5f5", // 授权页面背景颜色，默认值：#ffffff
					authButton: {
						normalColor: "#19be6b", // 授权按钮正常状态背景颜色 默认值：#3479f5
						highlightColor: "#18b566", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
						disabledColor: "#71d5a1", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
						textColor: "#ffffff", // 授权按钮文字颜色 默认值：#ffffff
						title: "本机号码一键登录" // 授权按钮文案 默认值：“本机号码一键登录”
					},
					privacyTerms: {
						suffix: "使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”
						termsColor: "#555555"
					}
				},
				data: {},
				success: data => {
					// 关闭一键登录的弹窗
					uni.closeAuthView();
					that.loginSuccess(data);
				},
				fail: res => {
					console.error(res);
					// 关闭一键登录的弹窗
					uni.closeAuthView();
					if (res.code === 30002) {
						// 如果失败，则自动切换为密码登录
						that.loginWay = "pwd";
					}
				}
			});
		},
		// 第三方登录 - 微信
		loginWeixin(data) {
			let that = this;
			let { agreement } = that;
			if (!agreement) {
				that.agreementLogin(() => {
					that.loginWeixin(data);
				});
				return;
			}
			let type = this.getWeixinLoginType();
			if (type === "none") {
				vk.alert("商家已禁用微信登录");
				return;
			}
			vk.userCenter.loginByWeixin({
				data: {
					...data,
					type
				},
				success: data => {
					that.loginSuccess(data);
				}
			});
		},
		getWeixinLoginType(){
			let that = this;
			let { platform, envH5 } = that;
			let platformObj = {
				"mp-weixin": "mp_weixin",
				"app-plus": "app"
			};
			let platformVal = platformObj[platform] || platform;
			if (platformVal === "h5" && envH5 === "h5-weixin") {
				platformVal = "h5_weixin";
			}
			let type = vk.getVuex(`$user.mchInfo.${platformVal}.weixin_login_type`) || "auto";
			return type;
		},
		// 微信公众号授权登录
		getH5WeixinCode() {
			let that = this;
			let { agreement } = that;
			if (!agreement) {
				that.agreementLogin(that.getH5WeixinCode);
				return;
			}
			let appid = vk.myfn.user.getH5WeixinAppid();
			let scope = "snsapi_userinfo"; // snsapi_userinfo授权可以获得昵称和头像
			let redirect_uri = window.location.href.split("?")[0];
			let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=login#wechat_redirect`;
			window.location.href = url;
		},
		// 登录成功后的统一执行逻辑
		loginSuccess(data, mode = 0) {
			let that = this;
			vk.setStorageSync("vkmall-login.agreement", true);
			if (mode === 0) {
				// mode为0代表需要进行一些判断
				let show = false;
				// 如果有昵称或头像未设置，则弹窗进行设置
				// 如果不希望每次登录都弹窗设置，可以考虑增加判断 data.type === "register" 这样只会在注册的时候弹窗一次
				if (vk.pubfn.isNullOne(data.userInfo.avatar, data.userInfo.nickname)) {
					// 需要显示弹窗
					show = true;
				}
				// 如果是注册，且没有邀请码，则额外进行邀请码的填写
				let needInviteCode = data.type === "register" && !data.userInfo.inviter_lock && vk.pubfn.isNull(data.userInfo.inviter_uid);
				if (needInviteCode) {
					// 需要显示邀请码的输入框
					that.updateUserInfoPopup.needInviteCode = needInviteCode;
					// 需要显示弹窗
					show = true;
				}
				if (show) {
					that.updateUserInfoPopup.data = data;
					that.updateUserInfoPopup.show = true;
					return;
				}
			}
			vk.toast("登陆成功!", 600, () => {
				// 检查是否有指定跳转的页面
				let app = getApp();
				if (typeof app.init == "function") app.init();
				if (vk.navigate.getOriginalPage()) {
					vk.navigate.originalTo();
					return false;
				}
				// 跳转到首页,或页面返回
				let pages = getCurrentPages();
				if (pages.length >= 2 && pages[pages.length - 2].route && pages[pages.length - 2].route.indexOf("login") == -1) {
					const eventChannel = that.getOpenerEventChannel();
					eventChannel.emit("loginSuccess", {});
					// 页面返回
					vk.navigateBack();
				} else {
					// 进入首页
					vk.navigateToHome();
				}
			});
		},
		codeError(res) {
			if (res.notExists) {
				let mobile = this.form1.mobile;
				vk.navigateTo(`./register?mobile=${mobile}`);
			}
		},
		// 点击同意协议按钮事件
		agreementLogin(callback) {
			vk.confirm("是否已查看并同意用户协议内容?", "提示", "同意", "再看看", res => {
				if (res.confirm) {
					this.userAgreement();
					if (typeof callback === "function") {
						callback();
					}
				}
			});
		},
		// 同意用户协议
		userAgreement() {
			this.agreement = true;
			vk.setStorageSync("vkmall-login.agreement", true);
		},
		// 打开隐私协议页面
		openPrivacyContract() {
			uni.openPrivacyContract({
				fail: err => {
					console.error("err: ", err);
					uni.showToast({
						title: "网络错误",
						icon: "error"
					});
				}
			});
		}
	},
	// 计算属性
	computed: {}
};
</script>
<style lang="scss" scoped>
@import url("./css/main.css");
.login-way-change {
	display: flex;
	padding: 0 80rpx;
	align-items: center;
	height: 50rpx;
	.login-way-left {
		.checkbox {
			transform: scale(0.7);
		}
	}
	.login-way-right {
		flex: 1;
		text-align: right;
	}
}
</style>
